<?php

namespace App\Services;

use App\RiskOrder;
use App\RiskRule;
use App\RiskRuleAli;
use Illuminate\Support\Facades\DB;

class RuleService
{

    public function checkCurtail($data,$param)
    {

        $level = 0;
        $a=$b=$c=$d=$s=0;
        $rule_list = RiskRule::getRuleList();
        $mingzhi = [];
        foreach ($rule_list as $key => $value){
            $result = $this->judgingData($data,$value);
            if($result['status']){
                $$key = 1;
                $mingzhi = array_merge($mingzhi,$result['mingzhi']);
            }
        }

        if($d){
            return $data;
        }


        $dq = RiskRule::getRuleDQ();
        $bairomg_service = new BairongService();
        foreach ($dq['d'] as  $val){
            $bairong_data = $bairomg_service->getStrategyData($param,$val['strategy_id']);

            $data = $this->mergeData($bairong_data,$data,$val['type'],$val['strategy_id']);

            foreach ($rule_list as $key => $value){
                $result = $this->judgingData($data,$value);
                if($result['status']){
                    $$key = 1;
                    $mingzhi = array_merge($mingzhi,$result['mingzhi']);
                }
            }

            if($d){
                return $data;
            }
        }

        foreach ($dq['q'] as  $val){
            if($val['type'] == 1){
                $bairong_data = $bairomg_service->getStrategyData($param,$val['strategy_id']);
            }else{
                $bairong_data = $bairomg_service->getInfoverifyData($param,$val['strategy_id']);
            }

            $data = $this->mergeData($bairong_data,$data,$val['type'],$val['strategy_id']);
        }

        return $data;
    }

    public function mergeData($bairong_data,$data,$type,$strategy_id)
    {
        $data[$strategy_id] = $bairong_data;
        $strategy_report_detail = $data['strategy_report_detail'];
        $infoverify_report_detail = $data['infoverify_report_detail'];
        foreach ($bairong_data as $key => $val){
            if($type == 1){
                if(!isset($strategy_report_detail[$key])){
                    $strategy_report_detail[$key] = $val;
                }
            }else{
                if(!isset($infoverify_report_detail[$key])){
                    $infoverify_report_detail[$key] = $val;
                }
            }
        }
        if(isset($bairong_data['Flag'])){
            foreach ($bairong_data['Flag'] as $key => $val){
                if($type == 1){
                    if(!isset($strategy_report_detail['Flag'][$key])){
                        $strategy_report_detail['Flag'][$key] = $val;
                    }
                }else{
                    if(!isset($infoverify_report_detail['Flag'][$key])){
                        $infoverify_report_detail['Flag'][$key] = $val;
                    }
                }
            }
        }
        if(isset($bairong_data['Rule']['hit_rules'])){
            foreach ($bairong_data['Rule']['hit_rules'] as $key => $val){
                if($type == 1){
                    if(!isset($strategy_report_detail['Rule']['hit_rules'][$key])){
                        $strategy_report_detail['Rule']['hit_rules'][$key] = $val;
                    }
                }else{
                    if(!isset($infoverify_report_detail['Rule']['hit_rules'][$key])){
                        $infoverify_report_detail['Rule']['hit_rules'][$key] = $val;
                    }
                }
            }
        }

        $data['strategy_report_detail'] = $strategy_report_detail;
        $data['infoverify_report_detail'] = $infoverify_report_detail;
        return $data;
    }

    public function getAllBairong($order)
    {
        /** @var RiskOrder $order */
        $data = json_decode($order->data,true);
        $data['money'] = $order->money;
        $data['age'] = 0;
        //数据处理
        $entryListNew = [];
        if(!empty($data['infoverify_report_detail']['CourtDetailPro']['entryList'])){
            foreach ($data['infoverify_report_detail']['CourtDetailPro']['entryList'] as $val){
                if(isset($entryListNew[$val['dataType']])){
                    if($entryListNew[$val['dataType']]['matchRatio'] < $val['matchRatio']){
                        $entryListNew[$val['dataType']] = $val;
                    }
                }else{
                    $entryListNew[$val['dataType']] = $val;
                }
            }
        }
        $data['infoverify_report_detail']['CourtDetailPro']['entryListNew'] = $entryListNew;

        if($order->id_card){
            $age = $this->getAgeFromId($order->id_card);
            if($age){
                $data['age'] = $age;
            }
        }

        $param = [
            'id_card' => $order->id_card,
            'name' => $order->id_name,
            'mobile' => $order->mobile,
        ];

        $dq = RiskRule::getRuleDQ();
        $bairomg_service = new BairongService();
        foreach ($dq['all'] as  $val){
            if(empty($data[$val['strategy_id']])){

                if($val['type'] == 1){
                    $bairong_data = $bairomg_service->getStrategyData($param,$val['strategy_id']);
                }else{
                    $bairong_data = $bairomg_service->getInfoverifyData($param,$val['strategy_id']);
                }
                $data = $this->mergeData($bairong_data,$data,$val['type'],$val['strategy_id']);
            }
        }
        $order->data = json_encode($data);
        $order->save();
        DB::table('ims_ewei_shop_order_detail')->where('orderid',$order->orderid)->update(['bairong_report'=>$order->data]);

        DB::table('ims_ewei_shop_member_detail')->where('openid',$order->openid)->update(['bairong_report'=>$order->data]);

    }

    public function updateLevel($order)
    {
        /** @var RiskOrder $order */
        $data = json_decode($order->data,true);
        $data['money'] = $order->money;
        $data['age'] = 0;
        //数据处理
        $entryListNew = [];
        if(!empty($data['infoverify_report_detail']['CourtDetailPro']['entryList'])){
            foreach ($data['infoverify_report_detail']['CourtDetailPro']['entryList'] as $val){
                if(isset($entryListNew[$val['dataType']])){
                    if($entryListNew[$val['dataType']]['matchRatio'] < $val['matchRatio']){
                        $entryListNew[$val['dataType']] = $val;
                    }
                }else{
                    $entryListNew[$val['dataType']] = $val;
                }
            }
        }
        $data['infoverify_report_detail']['CourtDetailPro']['entryListNew'] = $entryListNew;

        if($order->id_card){
            $age = $this->getAgeFromId($order->id_card);
            if($age){
                $data['age'] = $age;
            }
        }

        $level = 0;
        $a=$b=$c=$d=$s=0;


        //确定是否要增加百融数据
        if(empty($order->is_curtail) && !isset($data['strategy_report_detail']['ApplyLoanC'])){

            $order->is_curtail = 1;
            $order->save();
            $param = [
                'id_card' => $order->id_card,
                'name' => $order->id_name,
                'mobile' => $order->mobile,
            ];
            // var_dump(99999);
            $data_merge = $this->checkCurtail($data,$param);
            if(count($data_merge) != count($data)){
                $data = $data_merge;
                $order->data = json_encode($data);
                $order->save();
                //修改会员和订单数据
                DB::table('ims_ewei_shop_order_detail')->where('orderid',$order->orderid)->update(['bairong_report'=>$order->data]);

                DB::table('ims_ewei_shop_member_detail')->where('openid',$order->openid)->update(['bairong_report'=>$order->data]);
            }


        }

        $rule_list = RiskRule::getRuleList();
        $mingzhi = [];
        foreach ($rule_list as $key => $val){
            $result = $this->judgingData($data,$val);
            if($result['status']){
                $$key = 1;
                $mingzhi = array_merge($mingzhi,$result['mingzhi']);
            }
        }
        if($d){
            $level = 1;
        }elseif($c){
            $level = 2;
        }elseif($s){
            $level = 10;
        }elseif($a){
            $level = 4;
        }elseif($b){
            $level = 3;
        }
        if($order->status == 2 || $level != $order->dengji){
            $order->dengji = $level;
            $order->status = 3;
            $order->save();
            $y_order = DB::table('ims_ewei_shop_order')->where('ordersn',$order->ordersn)->first();
            if($y_order){
                DB::table('ims_ewei_shop_member')->where('openid',$y_order->openid)->update(['level'=>$level]);
                //不是D等级，启用智租
                if( $level != 1){
                    DB::table('ims_ewei_shop_order')->where('id',$order->orderid)->update(['is_reported'=>3]);
                }
            }



        }

        if($order->data_ali){
            $data_ali = json_decode($order->data_ali,true);
            if(!empty($data_ali['code']) && $data_ali['code'] == 10000){
                //有智租数据
                try{
                    $rule_list = RiskRuleAli::getRuleList();
                    $rank = RiskRuleAli::getRiskRank();
                    $zhfx = isset($data_ali['risk_rank'])?$data_ali['risk_rank']:0;
                    $gzfx = isset($data_ali['sub_rent_risk_result']['multi_rent_risk']['risk_rank'])?$data_ali['sub_rent_risk_result']['multi_rent_risk']['risk_rank']:0;
                    $yqfx = isset($data_ali['sub_rent_risk_result']['overdue_risk']['risk_rank'])?$data_ali['sub_rent_risk_result']['overdue_risk']['risk_rank']:0;
                    $c_data = [
                        'zhfx' => $zhfx,
                        'gzfx' => $gzfx,
                        'yqfx' => $yqfx,
                    ];
                    foreach ($rule_list as  $val){
                        $ali_status = true;
                        foreach ($c_data as $k => $v){
                            $ali_status = $ali_status && $v == $rank[$val[$k]];
                            if(!$ali_status){
                                break;
                            }
                        }

                        if($ali_status){
                            //验证年龄和金额

                            if($val['money'] || $val['age']){

                                $result = $this->checkExArrayData(json_decode($val['ultimately'],true),$data);
                                if(!$result){
                                    continue;
                                }
                            }


                            //匹配上
                            if($order->rule_ali_id != $val['id']){
                                $order->dengji_ali = $val['level'];
                                $order->rule_ali_id = $val['id'];
                                $order->save();
                                if(empty($y_order)){
                                    $y_order = DB::table('ims_ewei_shop_order')->where('ordersn',$order->ordersn)->first();
                                }
                                if($y_order){
                                    DB::table('ims_ewei_shop_member')->where('openid',$y_order->openid)->update(['dengji_ali'=>$val['level']]);
                                }
                            }

                            break;
                        }

                    }
                }catch (\Exception $e){
                    \Log::channel('verify')->info('订单id:'.$order->id,[$e->getMessage()]);
                }
            }
        }


        $rul = ['level' => $level,'mingzhi' => $mingzhi];

        return $rul;
    }
    public function judgingData($data,$list)
    {
        $result = [
            'status' => false,
            'mingzhi' => [],
        ];
        $mingzhi = [];
        foreach ($list as $val){
            $re = $this->checkExArrayData($val['and'],$data);
            if($re){
                $result['status'] = true;
                $mingzhi[] = [
                    'number' => $val['number'],
                    'name' => $val['name'],
                ];
//                break;
            }
        }
        $result['mingzhi'] =  $mingzhi;
        return $result;
    }



    public function checkExArrayData($v,$get_data)
    {
        $result = true;
        if(empty($v)){
            return false;
        }
        foreach ($v as $val){

            if(is_array($val[0])){
                $r = false;
                foreach ($val as $val_v){
                    $r = $r || $this->checkExData($val_v,$get_data);

                }
                $re = $r;

            }else{
                $re = $this->checkExData($val,$get_data);
            }
            if($re == false){
                return false;
            }
        }
        return $result;


    }


    public function checkExData($v,$get_data)
    {
        $result = false;

        if(is_array($v)){
            $number = $this->getExData($v[0],$get_data);

            if($number === false) return $result;
            switch ($v[1]){
                case 'bao':

                    if($number){
                        $number_v = explode(',',$v[2]);
                        if($number >= $number_v[0] && $number <= $number_v[1]){
                            $result = true;
                        }
                    }
                    break;
                case '>=':

                    if( $number >= $v[2]){
                        $result = true;
                    }
                    break;
                case '<=':
                    if( $number <= $v[2]){
                        $result = true;
                    }
                    break;
                case '==':

                    if( $number == $v[2]){
                        $result = true;
                    }
                    break;
                case '>':

                    if( $number > $v[2]){
                        $result = true;
                    }
                    break;


                case '<':
                    if( $number < $v[2]){
                        $result = true;
                    }
                    break;
                case 'count':
                    if(is_array($number)){
                        $number = count($number);
                        if($number >= $v[2]){
                            $result = true;
                        }
                    }
                    break;
            }
        }else{
            $number = $this->getExData($v,$get_data);
            if(!empty($number)){
                $result = true;
            }
        }

        return $result;
    }

    public function getExData($key,$data)
    {

        $kk = explode('.',$key);

        foreach ($kk as  $val){
            $data = isset($data[$val])?$data[$val]:'';
        }


        if($data === ''){
            $data = 0;
        }
        return $data;
    }

    public function getAgeFromId($id) {
        if (!preg_match('/^\d{17}[\dx]$/i', $id)) {
            return false;
        }

        $id = strtolower($id);
        $year = substr($id, 6, 4);
        $month = substr($id, 10, 2);
        $day = substr($id, 12, 2);

        $birthday = strtotime($year . '-' . $month . '-' . $day);
        if (!$birthday) {
            return false;
        }

        $age = (int) ((time() - $birthday) / (365 * 24 * 3600));
        return $age;
    }


    public function dataTranslate($order)
    {
        $bairong = json_decode($order->data, true);
        if(empty($bairong['infoverify_report_detail']['TelCheck_s']['result'])){
            $TelCheck_s = '查无此号';
        }else{
            $TelCheck_s = $bairong['infoverify_report_detail']['TelCheck_s']['result']=='1'?'一致':'不一致';
        }
        if(empty($bairong['infoverify_report_detail']['TelStatus']['data']['value'])){
            $TelStatus = '无结果';
        }else{

            $TelStatus = $this->tel_name[$bairong['infoverify_report_detail']['TelStatus']['data']['value']];
        }
        $Rule_C_CourtDetailPro = '';

        if(!empty($bairong['strategy_report_detail']['Rule']['hit_rules']['rule_c_courtdetailpro'])){
            foreach ($bairong['strategy_report_detail']['Rule']['hit_rules']['rule_c_courtdetailpro'] as $key => $val){
                $Rule_C_CourtDetailPro .= $key .'-'.$val['name_rule'].'<br>';
            }
        }
        $ApplyLoanStr = [

        ];




        $data = [
            'TelCheck_s' => $TelCheck_s,
            'TelStatus' => $TelStatus,
            'Rule_C_CourtDetailPro' => $Rule_C_CourtDetailPro, //信息验证规则-法院信息详情个人高级版
            'ApplyLoanStr' => $ApplyLoanStr,

        ];
        return $data;
    }
}
